package com.hopu.oa.controller.process;

import com.hopu.oa.dao.process.BursementDao;
import com.hopu.oa.entity.management.AoaTypeList;
import com.hopu.oa.entity.process.*;
import com.hopu.oa.entity.user.AoaUser;
import com.hopu.oa.service.impl.process.BursementServiceImpl;
import com.hopu.oa.service.impl.process.auditServiceImpl;

import com.hopu.oa.until.MoneyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class auditController {
    @Autowired
    private auditServiceImpl auditService;

    @Autowired
    private BursementDao bursementDao;

    @Autowired
    private BursementServiceImpl bursementService;

    @RequestMapping("/xinxeng")
    public String xinXeng(Model model) {
        return "process/procedure";
    }

    @RequestMapping("/audit")
    public String audit(String find, Model model, HttpSession session, @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "10") int size) {
        AoaUser aoaUser = (AoaUser) session.getAttribute("user");
        int totalElements = auditService.findAll(aoaUser.getUserId(), find, 0, 0).size();
        //有几页
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
        List<ProcessAll> all = auditService.findAll(aoaUser.getUserId(), find, (page - 1) * size, size);
        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);
        map1.put("number", page);
        map1.put("size", size);

        model.addAttribute("page", map1);
        model.addAttribute("prolist", all);
        model.addAttribute("find", find);
        model.addAttribute("url", "audtable");
        return "process/auditing";
    }

    @RequestMapping("/audtable")
    public String audtable(String find, Model model, HttpSession session, @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "10") int size) {
        AoaUser aoaUser = (AoaUser) session.getAttribute("user");
        int totalElements = auditService.findAll(aoaUser.getUserId(), find, 0, 0).size();
        //有几页
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
        List<ProcessAll> all = auditService.findAll(aoaUser.getUserId(), find, (page - 1) * size, size);
        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);
        map1.put("number", page);
        map1.put("size", size);

        model.addAttribute("page", map1);
        model.addAttribute("prolist", all);
        model.addAttribute("find", find);
        model.addAttribute("url", "audtable");
        return "process/audtable";
    }


    @RequestMapping("particular")
    public String particular(Model model, Integer processId, Integer page, String typeName, String remove) {
        System.out.println("processId = " + processId);
        System.out.println("typeName = " + typeName);
        System.out.println("remove = " + remove);
        model.addAttribute("remove", remove);
        model.addAttribute("page", page);
        model.addAttribute("processId", processId);

        //查询全部
        AoaProcessList aoaProcessList = bursementService.selectById(processId);
        HashMap<String, Object> maps = new HashMap<>();

//        预览图片，获取路径
        Integer proFileId = aoaProcessList.getProFileId();
        if (!Objects.isNull(proFileId)) {
            AoaAttachmentList aoaAttachmentList = bursementDao.selectAoaAttachmentList(proFileId);
            maps.put("file", aoaAttachmentList);
            maps.put("filePath", aoaAttachmentList.getAttachmentPath());
            System.out.println(aoaAttachmentList.getAttachmentPath());
            maps.put("fileType", "img");

        } else {
            maps.put("file", "file");
            maps.put("fileType", "bigImg");
        }
        HashMap<String, String> map = new HashMap<>();

        if (typeName.equals("费用报销") == true) {
            AoaBursement aoaBursement = bursementService.selectAllBursement(processId);

            AoaUser aoaUser = bursementService.selectByProcessUserIdAfter(aoaBursement.getUserName());//证明人

            AoaTypeList aoaTypeList = bursementService.selectByTypeId(aoaBursement.getAoaProcessList().getDeeplyId());
            AoaUser aoaUser1 = bursementService.selectByProcessUserIdAfter(aoaBursement.getOperationName());
            List<AoaDetailsburse> aoaDetailsburses = bursementService.selectByBursementIdAfter(aoaBursement.getBursementId());

            map.put("typename", typeName);
            map.put("processName", aoaBursement.getAoaProcessList().getProcessName());
            map.put("harryname", aoaTypeList.getTypeName());//紧急程度
            map.put("username", aoaBursement.getAoaUser().getUserName());//申请人、报销人员
            map.put("deptname", aoaBursement.getAoaDept().getDeptName());
            map.put("applytime", aoaBursement.getAoaProcessList().getApplyTime());
            map.put("zhengmingren", aoaUser.getUserName());//证明人
            map.put("name", aoaBursement.getName());
            map.put("type", aoaBursement.getAoaTypeList().getTypeName());
            map.put("audit", aoaUser1.getUserName());
            map.put("burseTime", aoaBursement.getBurseTime());//报销日期
            map.put("allinvoices", aoaBursement.getAllinvoices().toString());//票据总数
            map.put("managerAdvice", aoaBursement.getManagerAdvice());
            map.put("financialAdvice", aoaBursement.getFinancialAdvice());
            map.put("allMoney", aoaBursement.getAllMoney().toString());
            map.put("money", MoneyUtil.toChinese(aoaBursement.getAllMoney().toString()));
            map.put("processDescribe", aoaBursement.getAoaProcessList().getProcessDes());

            model.addAttribute("maps", maps);
            model.addAttribute("map", map);
            model.addAttribute("detaillist", aoaDetailsburses);
            return "process/serch";//费用报销单

        } else if (typeName.equals("出差申请") == true) {
            AoaEvection aoaEvection = bursementService.selectEvectionByProcessId(processId);
            AoaTypeList aoaTypeList = bursementService.selectByTypeId(aoaEvection.getAoaProcessList().getDeeplyId());

            map.put("typename", typeName);
            map.put("processName", aoaEvection.getAoaProcessList().getProcessName());
            map.put("harryname", aoaTypeList.getTypeName());//紧急程度
            map.put("username", aoaEvection.getAoaUser().getUserName());
            map.put("deptname", aoaEvection.getAoaDept().getDeptName());
            map.put("applytime", aoaEvection.getAoaProcessList().getApplyTime());
            map.put("startime", aoaEvection.getAoaProcessList().getStartTime());
            map.put("endtime", aoaEvection.getAoaProcessList().getEndTime());
            if (aoaEvection.getAoaProcessList().getProcseeDays() != null) {
                map.put("tianshu", aoaEvection.getAoaProcessList().getProcseeDays().toString());
            }
            map.put("processDescribe", aoaEvection.getAoaProcessList().getProcessDes());
            map.put("managerAdvice", aoaEvection.getManagerAdvice());
            map.put("personnelAdvice", aoaEvection.getPersonnelAdvice());
            map.put("name", aoaEvection.getAoaProcessList().getTypeName());

            model.addAttribute("maps", maps);
            model.addAttribute("map", map);
            model.addAttribute("statusid", aoaEvection.getAoaProcessList().getStatusId());
            return "process/eveserach";//出差申请单

        } else if (typeName.equals("出差费用") == true) {

            AoaEvectionmoney aoaEvectionmoney = bursementService.selectEvectionmoneyByProcessId(processId);
            AoaTypeList aoaTypeList = bursementService.selectByTypeId(aoaEvectionmoney.getAoaProcessList().getDeeplyId());
            List<AoaStay> aoaStay = bursementService.selectStayByEvectionmoneyId(aoaEvectionmoney.getEvectionmoneyId());
            List<AoaTraffic> aoaTraffic = bursementService.selectTrafficBy(aoaEvectionmoney.getEvectionmoneyId());
            Integer staymoney = 0;
            Integer tramoney = 0;

            for (int i = 0; i < aoaStay.size(); i++) {
                staymoney += aoaStay.get(i).getStayMoney();
            }
            System.out.println("staymoney = " + staymoney);
            for (int i = 0; i < aoaTraffic.size(); i++) {
                tramoney += aoaTraffic.get(i).getTrafficMoney();
            }
            System.out.println("tramoney = " + tramoney);
            map.put("typename", typeName);
            map.put("processName", aoaEvectionmoney.getAoaProcessList().getProcessName());
            map.put("harryname", aoaTypeList.getTypeName());//紧急程度
            map.put("username", aoaEvectionmoney.getAoaUser().getUserName());
            map.put("deptname", aoaEvectionmoney.getAoaDept().getDeptName());
            map.put("applytime", aoaEvectionmoney.getAoaProcessList().getApplyTime());
            map.put("startime", aoaEvectionmoney.getAoaProcessList().getStartTime());
            map.put("endtime", aoaEvectionmoney.getAoaProcessList().getEndTime());
            map.put("tianshu", aoaEvectionmoney.getAoaProcessList().getProcseeDays().toString());
            map.put("processDescribe", aoaEvectionmoney.getAoaProcessList().getProcessDes());
            map.put("name", aoaEvectionmoney.getAoaProcessList().getTypeName());
            map.put("managerAdvice", aoaEvectionmoney.getManagerAdvice());
            map.put("financialAdvice", aoaEvectionmoney.getFinancialAdvice());
            if (aoaEvectionmoney.getPro() != null) {
                map.put("pro", aoaEvectionmoney.getPro().toString());
            }
            Integer allmoney = staymoney + tramoney;
            model.addAttribute("staymoney", staymoney);
            model.addAttribute("tramoney", tramoney);

            model.addAttribute("allmoney", MoneyUtil.toChinese(allmoney.toString()));
            model.addAttribute("staylist", aoaStay);
            model.addAttribute("tralist", aoaTraffic);
            model.addAttribute("map", map);
            model.addAttribute("maps", maps);
            return "process/evemonserch";//出差费用表

        } else if (typeName.equals("离职申请") == true) {
            AoaResign aoaResign = bursementService.selectResignByByProcessId(processId);
            AoaTypeList aoaTypeList = bursementService.selectByTypeId(aoaResign.getAoaProcessList().getDeeplyId());
            AoaUser aoaUser = bursementService.selectByProcessUserIdAfter(aoaResign.getHandUser());//证明人

            map.put("typename", typeName);
            map.put("processName", aoaResign.getAoaProcessList().getProcessName());
            map.put("harryname", aoaTypeList.getTypeName());//紧急程度
            map.put("username", aoaResign.getAoaUser().getUserName());
            map.put("deptname", aoaResign.getAoaDept().getDeptName());
            map.put("applytime", aoaResign.getAoaProcessList().getApplyTime());
            map.put("handUser", aoaUser.getUserName());
            map.put("nofinish", aoaResign.getNofinish());
            map.put("processDescribe", aoaResign.getAoaProcessList().getProcessDes());
            map.put("managerAdvice", aoaResign.getManagerAdvice());
            map.put("financialAdvice", aoaResign.getFinancialAdvice());
            map.put("personnelAdvice", aoaResign.getPersonnelAdvice());
            System.out.println(aoaResign.getPersonnelAdvice());
            model.addAttribute("finish", aoaResign.getIsFinish());
            model.addAttribute("statusId", aoaResign.getAoaProcessList().getStatusId());
            model.addAttribute("map", map);
            return "process/resserch";

        } else if (typeName.equals("请假申请") == true) {
            AoaHoliday holiday = bursementService.selectByID(processId);

            AoaHoliday aoaHoliday = bursementService.selectByProID(processId);

            model.addAttribute("maps", maps);
            model.addAttribute("map", aoaProcessList);
            model.addAttribute("type", aoaHoliday);
            model.addAttribute("eve", holiday);
            model.addAttribute("statusId", aoaProcessList.getStatusId());
            return "process/holiserch";

        } else if (typeName.equals("转正申请") == true) {
            AoaRegular aoaRegular = bursementService.selectRegularByProcessId(processId);
            AoaTypeList aoaTypeList = bursementService.selectByTypeId(aoaRegular.getAoaProcessList().getDeeplyId());

            map.put("typename", typeName);
            map.put("processName", aoaRegular.getAoaProcessList().getProcessName());
            map.put("harryname", aoaTypeList.getTypeName());//紧急程度
            map.put("username", aoaRegular.getAoaUser().getUserName());
            map.put("deptname", aoaRegular.getAoaDept().getDeptName());
            map.put("applytime", aoaRegular.getAoaProcessList().getApplyTime());
            map.put("startime", aoaRegular.getAoaProcessList().getStartTime());
            map.put("endtime", aoaRegular.getAoaProcessList().getEndTime());
            map.put("tianshu", aoaRegular.getAoaProcessList().getProcseeDays().toString());
            map.put("experience", aoaRegular.getExperience());
            map.put("understand", aoaRegular.getUnderstand());
            map.put("pullulate", aoaRegular.getPullulate());
            map.put("deficiency", aoaRegular.getDeficiency());
            map.put("dobetter", aoaRegular.getDobetter());
            map.put("advice", aoaRegular.getAdvice());
            map.put("managerAdvice", aoaRegular.getManagerAdvice());
            map.put("personnelAdvice", aoaRegular.getPersonnelAdvice());
            map.put("processDescribe", aoaRegular.getAoaProcessList().getProcessDes());

            model.addAttribute("statusId", aoaRegular.getAoaProcessList().getStatusId());
            model.addAttribute("map", map);
            return "process/reguserch";

        } else if (typeName.equals("加班申请") == true) {
            AoaOvertime overtime = bursementService.selectByProId(processId);
            AoaOvertime aoaOvertime = bursementService.selectOverAndTypeById(processId);
            String type = aoaOvertime.getAoaTypeList().getTypeName();//加班类型

            model.addAttribute("type", type);
            model.addAttribute("eve", overtime);
            model.addAttribute("map", aoaProcessList);
            model.addAttribute("statusId", aoaProcessList.getStatusId());
            return "process/overserch";
        }
        return "process/evemonserch";
    }

    @RequestMapping("sdelete")
    public String sdelete(Model model, String processId, Integer page) {
        System.out.println("processId = " + processId);
        System.out.println("page = " + page);
        int i = auditService.deleteProcess(Integer.parseInt(processId));
        System.out.println("i = " + i);
        return "redirect:audit?page=" + page;
    }


    /**
     * 审核
     *
     * @param processId
     * @param model
     * @param session
     * @param userName
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("auditing")
    public String auditing(Integer processId, Model model, HttpSession session,
                           String userName, Integer nowpage,
                           @RequestParam(value = "page", defaultValue = "1") int page,
                           @RequestParam(value = "size", defaultValue = "5") int size) {
        AoaUser aoaUser = (AoaUser) session.getAttribute("user");
        int id = processId;
        AoaUser user = (AoaUser) session.getAttribute("user");
        int totalElements = auditService.findUserInfoByName(aoaUser.getUserId(), userName, page, 0, user.getRoleId()).size();
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
        List<AoaUser> userInfoo = auditService.findUserInfoByName(aoaUser.getUserId(), userName, (page - 1) * size, size, user.getRoleId());
        System.out.println(userName);
        System.out.println("processId = " + processId);

        HashMap<String, Integer> map = new HashMap<>();
        map.put("totalElements", totalElements);
        map.put("totalPages", totalPages);
        map.put("number", page);
        map.put("size", size);
        model.addAttribute("id", id);
        model.addAttribute("page", map);
        model.addAttribute("userName", userName);
        model.addAttribute("userInfo", userInfoo);
        model.addAttribute("nowpage", nowpage);
        model.addAttribute("url", "auditingg");
        model.addAttribute("positionId", user.getPositionId());
        AoaProcessList processList = auditService.selectOneById(id);
        List<AoaReviewed> revieweds = auditService.selectReviewedByid(id);
        AoaReviewed aoaReviewed = auditService.selectByid(processId, user.getUserId());
        //总经理登录时，判断之前的人是否审核完
        List<AoaReviewed> list = auditService.selectReviewedStatusId(processId);
        List<Integer> aoaReviewedStatusId = new ArrayList<>();
        System.out.println(list);
        if (aoaUser.getPositionId() == 3) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getUserId() == 3) {
                    list.remove(list.get(i));
                }
            }
            for (int i = 0; i < list.size(); i++) {
                aoaReviewedStatusId.add(list.get(i).getStatusId());
            }

            if (aoaReviewedStatusId.contains(23) == true) {
                //之前有人未处理
                model.addAttribute("Deal", 0);
                System.out.println("前人未处理完");
            } else {
                //前人已处理完
                model.addAttribute("Deal", 1);
                System.out.println("前人已处理完");
            }
        }
        System.out.println(processList);
        System.out.println("processList.getStatusId()=" + processList.getStatusId());
        model.addAttribute("statusid", processList.getStatusId());
        String typename = processList.getTypeName().trim();
        if (("费用报销").equals(typename)) {
            AoaBursement bursement = auditService.selectBursementById(processList.getProcessId());
            model.addAttribute("bu", bursement);
        } else if (("出差费用").equals(typename)) {
            AoaEvectionmoney evectionMoney = auditService.selectEvectionMoneyById(processList.getProcessId());
            System.out.println(evectionMoney);
            model.addAttribute("bu", evectionMoney);
        }

        model.addAttribute("revie", revieweds);
        model.addAttribute("typename", typename);
        model.addAttribute("process", processList);

        model.addAttribute("statusid", aoaReviewed.getStatusId());
        model.addAttribute("positionid", user.getPositionId());
        return "process/audetail";
    }

    @RequestMapping("auditingg")
    public String auditingg(int processId, Model model, HttpSession session,
                            String userName,
                            @RequestParam(value = "page", defaultValue = "1") int page,
                            @RequestParam(value = "size", defaultValue = "5") int size) {
        AoaUser aoaUser = (AoaUser) session.getAttribute("user");
        int id = processId;
        AoaUser user = (AoaUser) session.getAttribute("user");
        int totalElements = auditService.findUserInfoByName(aoaUser.getUserId(), userName, page, 0, user.getRoleId()).size();
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
        List<AoaUser> userInfoo = auditService.findUserInfoByName(aoaUser.getUserId(), userName, (page - 1) * size, size, aoaUser.getRoleId());
        System.out.println(userName);

        HashMap<String, Integer> map = new HashMap<>();
        map.put("totalElements", totalElements);
        map.put("totalPages", totalPages);
        map.put("number", page);
        map.put("size", size);
        model.addAttribute("id", id);
        model.addAttribute("page", map);
        model.addAttribute("userName", userName);
        model.addAttribute("userInfo", userInfoo);
        model.addAttribute("url", "auditingg");
        model.addAttribute("positionId", user.getPositionId());
        System.out.println("processId = " + processId);
        AoaProcessList processList = auditService.selectOneById(id);
        List<AoaReviewed> revieweds = auditService.selectReviewedByid(id);
        AoaReviewed aoaReviewed = auditService.selectByid(processId, user.getUserId());


        //总经理登录时，判断之前的人是否审核完
        List<Integer> aoaReviewedStatusId = new ArrayList<>();
        if (aoaUser.getPositionId() == 3) {
            for (int i = 0; i < revieweds.size(); i++) {
                aoaReviewedStatusId.add(revieweds.get(i).getStatusId());
            }
            if (aoaReviewedStatusId.contains(23) == true) {
                //之前有人未处理
                model.addAttribute("Deal", 0);
                System.out.println("之前有人未处理");
            } else {
                //前人已处理完
                model.addAttribute("Deal", 1);
                System.out.println("前人已处理完");
            }
        }


        System.out.println(processList);
        String typename = processList.getTypeName().trim();
        System.out.println("processList.getStatusId()=" + processList.getStatusId());
        if (("费用报销").equals(typename)) {
            AoaBursement bursement = auditService.selectBursementById(processList.getProcessId());
            model.addAttribute("bu", bursement);
        } else if (("出差费用").equals(typename)) {
            AoaEvectionmoney evectionMoney = auditService.selectEvectionMoneyById(processList.getProcessId());
            System.out.println(evectionMoney);
            model.addAttribute("bu", evectionMoney);
        }

        model.addAttribute("revie", revieweds);
        model.addAttribute("typename", typename);
        model.addAttribute("process", processList);

        model.addAttribute("statusid", aoaReviewed.getStatusId());
        model.addAttribute("positionid", user.getPositionId());
        return "common/recivers";
    }


    @RequestMapping("susave")
    public String susave(Integer nowpage, int statusId, String username, String advice, int proId, String type, HttpSession session) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        System.out.println("username = " + username);
        System.out.println(statusId + "statusId" + username + "username" + advice + "advice" + "proId" + proId + "type" + type);
        Integer positionId = user.getPositionId();//审核人的职位编号
        String typeName = auditService.selectProcess(proId).getTypeName();

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);

        if (positionId == 3) {//总经理
            if (typeName.equals("费用报销") == true) {
                bursementService.ManagerAdviceBursement(proId, advice);
            } else if (typeName.equals("出差申请") == true) {
                bursementService.ManagerAdviceEvection(proId, advice);
            } else if (typeName.equals("转正申请") == true) {
                bursementService.ManagerAdviceRegular(proId, advice);
            } else if (typeName.equals("加班申请") == true) {
                bursementService.ManagerAdviceOvertime(proId, advice);
            } else if (typeName.equals("离职申请") == true) {
                bursementService.ManagerAdviceResign(proId, advice);
            } else if (typeName.equals("请假申请") == true) {
                bursementService.ManagerAdviceHoliday(proId, advice);
            } else if (typeName.equals("出差费用") == true) {
                bursementService.ManagerAdviceEvectionMoney(proId, advice);
            }
        } else if (positionId == 5) {//财务部经理
            if (typeName.equals("费用报销") == true) {
                bursementService.FinancialAdviceBursement(proId, advice);
            } else if (typeName.equals("离职申请") == true) {
                bursementService.FinancialAdviceResign(proId, advice);
            } else if (typeName.equals("出差费用") == true) {
                bursementService.FinancialAdviceEvectionMoney(proId, advice);
            }
        } else if (positionId == 7) {//人事部经理
            if (typeName.equals("加班申请") == true) {
                bursementService.personneAdviceOvertime(proId, advice);
            } else if (typeName.equals("出差申请") == true) {
                bursementService.personneAdviceEvection(proId, advice);
            } else if (typeName.equals("离职申请") == true) {
                bursementService.personneAdviceResign(proId, advice);
            } else if (typeName.equals("转正申请") == true) {
                bursementService.personneAdviceRegular(proId, advice);
            } else if (typeName.equals("请假申请") == true) {
                bursementService.personneAdviceHoliday(proId, advice);
            }
        }

        if (username != null && username != "") {
            //审核流转

            auditService.updateReviewed(advice, dateString, statusId, proId, user.getUserId());
            if (statusId == 26) {//未通过
                auditService.updateProcessByid(26, proId);
                //若其他审批人已流转，则删除未处理的
                auditService.deleteReviewedByNoDeal(proId);
            } else {//通过
                auditService.updateProcessByid(24, proId);
                int id = auditService.selectIDByName(username);
                System.out.println(id);

                if (auditService.selectReviewedYN(proId, id) != null) {
                    //已流转过
                    System.out.println("已流转过");
                    //无操作
                } else {
                    auditService.insertIntoReviewed(proId, id);
                }
            }

        } else {
            //审核结案
            //判断其他人是否都处理完

            auditService.updateReviewed(advice, dateString, statusId, proId, user.getUserId());
            auditService.updateReviewedAllUser(statusId, proId);

            auditService.updateProcessByid(statusId, proId);
        }
        return "redirect:audit?page=" + nowpage;
    }

}
